﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace MusicDownload
{
    public class DelayLogic
    {
        private Thread thread;
        private AutoResetEvent restEvent = new AutoResetEvent(false);
        private long NextRunTime;
        private Action action;

        public DelayLogic()
        {
            thread = new Thread(new ThreadStart(OnThreadLogic));
            thread.IsBackground = true;
            thread.Start();
        }

        public void Register(int time, Action action)
        {
            lock (this)
            {
                NextRunTime = GetMillisecondTimestamp() + time;
                this.action = action;
            }

            this.restEvent.Set();
        }

        public void Cancel()
        {
            lock (this)
            {
                this.action = null;
            }
            
            this.restEvent.Set();
        }

        private void OnThreadLogic()
        {
            while (true)
            {
                this.restEvent.Reset();

                if (action == null)
                {
                    this.restEvent.WaitOne(1000 * 10);
                }
                else
                {
                    var waitTime = (int)(GetMillisecondTimestamp() - NextRunTime);
                    if (waitTime > 0)
                        this.restEvent.WaitOne(waitTime);
                }


                lock (this)
                {
                    if (action == null)
                        continue;

                    if (NextRunTime > GetMillisecondTimestamp())
                        continue;

                    action.Invoke();
                    action = null;
                }
            }
        }

        private long GetMillisecondTimestamp()
        {
            return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000;
        }
    }
}
